package com.sx.micowell.framework.model

import android.text.TextUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.mvvm.base.data.SingleLiveEvent
import com.example.mvvm.base.vm.BaseViewModel
import com.example.mvvm.rx.RxBus
import com.example.mvvm.until.LogUtils
import com.example.mvvm.until.SPUtils
import com.example.mvvm.until.ToastUtils
import com.example.mvvm.until.Utils
import com.google.gson.Gson
import com.miloyu.modelnet.network.ApiResponse
import com.miloyu.modelnet.network.HttpClient
import com.miloyu.modelnet.network.service.IApiService
import com.miloyu.modelnet.network.tools.RxUtils
import com.miloyu.modelnet.response.VersionVO
import com.miloyu.modelnet.response.VersionVOWrap
import com.sx.micowell.framework.app.AppConstant
import com.sx.micowell.framework.app.SPKey
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.binding.BindingCommand
import com.sx.micowell.framework.binding.impl.IBindingAction
import com.sx.micowell.framework.entity.AccountBean
import com.sx.micowell.framework.tools.AppDialogUtils
import com.sx.micowell.framework.tools.CacheUtils
import com.sx.micowell.framework.tools.EventInfo
import com.sx.micowell.framework.tools.setDataList
import com.tuya.smart.android.user.api.ILoginCallback
import com.tuya.smart.android.user.api.ILogoutCallback
import com.tuya.smart.home.sdk.TuyaHomeSdk
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

import java.util.HashMap

/**
 * @Author: YY
 * @Time: 2021/8/14
 * @Describe TODO
 */
class SettingModel : BaseViewModel() {

    override fun registerRxBus() {
        super.registerRxBus()
        addSubscribe(
            RxBus.getDefault().toObservable(EventInfo::class.java)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { event ->
                    if (event.type == AppConstant.EVENT_LOGIN_OUT) {
                        loginSwitchEvent.call()
                    } else if (event.type == AppConstant.EVENT_LOGIN_SWITCH){
                        loginSwitchEvent.call()
                    }
                }
        )
    }

    var loginSwitchEvent: SingleLiveEvent<Void> = SingleLiveEvent()

    var cacheSizeEvent: SingleLiveEvent<String> = SingleLiveEvent<String>()

    var loginOutEvent: SingleLiveEvent<Void> = SingleLiveEvent()

    var clearCacheEvent: SingleLiveEvent<Void> = SingleLiveEvent()

    var loginOutStateEvent: SingleLiveEvent<Void> = SingleLiveEvent()

    var updateVersionEvent: SingleLiveEvent<VersionVO> = SingleLiveEvent();

    var currentVersion: SingleLiveEvent<String> = SingleLiveEvent()

    // 个人资料
    var personalOnClickCommand = BindingCommand<Any>(IBindingAction {
        context.startContainerActivity(
            RouteManager.getInstance().getPersonalInfoFragment()::class.java.canonicalName
        )
    })

    // 修改登录密码
    var modifyPwdOnClickCommand = BindingCommand<Any>(IBindingAction {
        RouteManager.getInstance().intentRegisterToForgetPwd(
            2, SPUtils.getInstance().getString(SPKey.SP_PHONE)
        )
    })

    // 切换账号
    var switchAccountOnClickCommand = BindingCommand<Any>(IBindingAction {
        context.startContainerActivity(
            RouteManager.getInstance().getSwitchLoginFragment()::class.java.canonicalName
        )
    })

    // 检查版本更新
    var checkUpOnClickCommand = BindingCommand<Any>(IBindingAction {
        checkUpVersion()
    })

    // 清除缓存
    var clearCacheOnClickCommand = BindingCommand<Any>(IBindingAction {
        clearCacheEvent.call()
    })

    // 退出登录
    var loginOutOnClickCommand = BindingCommand<Any>(IBindingAction {
        loginOutEvent.call()
    })


    /**
     * 计算缓存大小
     */
    fun calculateCacheSize() {
        val cacheSize: String = CacheUtils.getTotalCacheSize(Utils.getContext())
        cacheSizeEvent.value = cacheSize
    }

    /**
     * 清除缓存
     */
    fun clearCache() {
        CacheUtils.clearAllCache(Utils.getContext())
        calculateCacheSize()
    }


    private fun checkUpVersion() {
        HttpClient.instance.create(IApiService::class.java)
            .checkUpVersion()
            .compose(RxUtils.compose())
            .subscribe(object : ApiResponse<VersionVOWrap>() {

                override fun success(data: VersionVOWrap?, msg: String?) {
                    LogUtils.d("checkUpVersion: " + data?.version?.androidurl)
                    updateVersionEvent.value = data?.version
                }

                override fun onFail(e: Throwable?, errorMsg: String?) {

                }

            })
    }

    fun loginOut(isSwitch: Boolean) {

        TuyaHomeSdk.getUserInstance().logout(object : ILogoutCallback {
            override fun onSuccess() {
                LogUtils.d("涂鸦退出登录成功")
            }
            override fun onError(code: String, error: String) {

            }
        })

        if (!isSwitch) {
            addSubscribe(
                HttpClient.instance.apiService
                    .loginOut()
                    .subscribeOn(Schedulers.io())
                    .subscribe()
            )
        }
        loginOutStateEvent.call()

    }

    fun saveAccount(phone: String, pwd: String, token: String) {
        val accountBean = AccountBean(phone, pwd, token)
        if (!TextUtils.isEmpty(SPUtils.getInstance().getString(SPKey.SP_ACCOUNT))) {
            val array: Array<AccountBean> = Gson().fromJson(
                SPUtils.getInstance().getString(SPKey.SP_ACCOUNT), Array<AccountBean>::class.java
            )
            val list = array.toMutableList()
            list.add(0, accountBean)
            setDataList(SPKey.SP_ACCOUNT, list.distinct())
        } else {
            val classTests = mutableListOf<AccountBean>()
            classTests.add(accountBean)
            setDataList(SPKey.SP_ACCOUNT, classTests)
        }
    }
}